//
//  WCNEffectServiceTimeVC.m
//  WCN
//
//  Created by wsj2015 on 15/12/14.
//  Copyright © 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNEffectServiceTimeVC.h"
#import "WCNSetTimeHeaderCRV.h"
#import "Macros.h"
#import "WCNEffectServiceTimeControll.h"
#import "WCButton.h"
#import "UINavigationItem+Offset.h"
#import "WCNetworkAccessManager.h"
#import "WCDefaultManager.h"

#import "WCNSetTimeCCell.h"
#import "WCNTemperiodIdForAdd.h"
#import "WCNTimePeriodModel.h"
#import "WCNEffectTimeForSelect.h"
#import "WCPopupLayerManager.h"
#import "NSString+Utilities.h"
#import "WSJAnimationTool.h"


static NSString *cellId = @"WCNSetTimeCCell";
static NSString *headerId = @"WCNSetTimeHeaderCRV";
static NSString *footerId = @"UICollectionReusableView";

#define cellId @"WCNSetTimeCCell"
#define kChooseHeight 106
#define kcollectionFrame CGRectMake(0, kChooseHeight, kScreenWidth, kScreenHeight -kChooseHeight -64-29)
@interface WCNEffectServiceTimeVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UIAlertViewDelegate>
{
    UICollectionView *_collectionView;
    NSMutableArray *_weekArray;
    NSMutableArray *_tiemPeriodArray;
    WCNEfffectServiceTimeType _timeType;
    WCNYearDate *_currentDay;
    
    WCNYearDate *_firstDate;
    NSInteger _weekDayId;
 
}
@end

@implementation WCNEffectServiceTimeVC


- (instancetype)init
{
    if (self =[super init]) {
        _tiemPeriodArray = [NSMutableArray array];
        _timeType = WCNEfffectServiceTimeTypeHospitalIn;
        _weekArray = [NSMutableArray array];
        _weekDayId = 1;
    }
    return self;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HexRGB_WSJ(236, 236, 236);
    // Do any additional setup after loading the view.
    
    
    [self configUI];
    [self createCollectionView];
    [self prepareData];
   
    

    
}
//"nurseId": 1,
//"workDate": "2016-01-05",
//"serviceTimeJSONArray": ""
- (void)configUI
{
    weakSelf_define;
    self.title  =@"当前生效时间";
    WCButton *rightBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
    [rightBtn addTarget:self action:@selector(saveCurrentDay) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationItem addRightBarButtonItem:rightBtn];

    WCNEffectServiceTimeControll *headView =[WCNEffectServiceTimeControll viewFromNib];
    headView.frame =CGRectMake(0,0, kScreenWidth, 170);
 
   
    [self.view addSubview:headView];
    
    headView.tiemTypeSlectBolck = ^(WCNEfffectServiceTimeType timeType){
        _timeType = timeType;
      
    };
    headView.lodingFinish =^(WCNYearDate *firstDay){
        _firstDate = firstDay;
    
    };
    headView.dateBlock =^(WCNYearDate *date){
        _currentDay = date;
        _weekDayId = [date.weekDayId integerValue];
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
        [weakSelf prepareData];
    
    };
        
   
   
 
}

- (void)prepareData{
    
    MBProgressHUD *hud =showHud;
    [[WCNetworkAccessManager sharedMg] POST:KserviceTimeList_part parameters:@{@"unit":@(6)} success:^(NSDictionary *responseObject) {
        [_tiemPeriodArray removeAllObjects];
        NSDictionary *data =responseObject[@"data"];
        for (NSDictionary *dict in data) {
            WCNTemperiodIdForAdd *model =[[WCNTemperiodIdForAdd alloc] init];
            [model setValuesForKeysWithDictionary:dict[@"currentServiceTime"]];
            model.isSelectItem = NO;
            
            [_tiemPeriodArray addObject:model];
        }
        [self getDaySelectTimeDataWith];
    } failure:nil netError:nil always:^{
        [hud hide:YES];
    }];
    

}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    [WSJAnimationTool animationMoveUp:cell duration:.35f];


}

- (void)getDaySelectTimeDataWith
{
    NSMutableDictionary *params =[NSMutableDictionary new];
   
    if (!_currentDay) {
        params[@"workDate"] = _firstDate.date;
        
    }else{
        params[@"workDate"] = _currentDay.date;

    
    }
    params[@"nurseId"] = @([[WCDefaultManager shareMg] nurseId]);
    

    [[WCNetworkAccessManager sharedMg] POST:kGetNurseServiceTimeByCondition parameters:params success:^(NSDictionary *responseObject) {
        NSMutableArray *array =[NSMutableArray array];
        for (NSDictionary *dict in responseObject[@"data"]) {
            WCNEffectTimeForSelect *selectTime =[[WCNEffectTimeForSelect alloc] init];
            [selectTime setValuesForKeysWithDictionary:dict];
            [array addObject:selectTime];
        }
        
        for (WCNEffectTimeForSelect *select in array) {
            for (WCNTemperiodIdForAdd *addModel in _tiemPeriodArray) {
                if ([select.timePeriodId integerValue] == [addModel.wcnId integerValue]) {
                    addModel.timeType =[select.hosptialTimeFlag integerValue];
                    addModel.isSelectItem = YES;
                }
                
            }
        }
        [_collectionView reloadData];
     
    } failure:nil netError:nil always:^{
        
    }];
    

}
- (void)pageBack
{
    UIAlertView *alerView =[[UIAlertView alloc] initWithTitle:@"提示" message:@"是否放弃本次编辑" delegate:self cancelButtonTitle:@"放弃" otherButtonTitles:@"继续", nil];
    alerView.tag = 3002;
    [alerView show];


}

- (void)saveCurrentDay
{

    UIAlertView *alerView =[[UIAlertView alloc] initWithTitle:@"提示" message:@"是否保存当前日的服务时间修改" delegate:self cancelButtonTitle:@"继续修改" otherButtonTitles:@"保存", nil];
    alerView.tag = 3001;
    [alerView show];

}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 3001) {
        if (buttonIndex ==1) {
            
            [self saveByPost];
            
        }
    }
    if (alertView.tag == 3002) {
        if (buttonIndex ==0) {
            
            [self.navigationController popViewControllerAnimated:YES];
            
        }
    }
    

}

- (void)saveByPost
{
    NSMutableArray *selectArray = [NSMutableArray array];
    for (WCNTemperiodIdForAdd *model in _tiemPeriodArray) {
        if (model.isSelectItem == YES) {
            [selectArray addObject:[model modelToDictionary]];
        }
    }
//    "nurseId": 1,
//    "workDate": "2016-01-05",
//    "serviceTimeJSONArray": ""
    MBProgressHUD *hud = showHud;
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    params[@"nurseId"] =@([[WCDefaultManager shareMg] nurseId]);
    if (_currentDay) {
        params[@"workDate"] =_currentDay.date;
    }else{
        params[@"workDate"] =_firstDate.date;
    }
    
    params[@"serviceTimeJSONArray"]=[NSString dataToJsonString:selectArray];
//    weakSelf_define;
     [[WCNetworkAccessManager sharedMg] POST:kSaveDailyServiceTime parameters:params success:^(NSDictionary *responseObject) {
         
         [[WCPopupLayerManager shareMg] showTextOnly:responseObject[@"data"] withView:[UIApplication sharedApplication].keyWindow];
         
     } failure:nil netError:nil always:^{
         [hud hide:YES];
     }];
    
    


}


- (void)createCollectionView
{
    CGRect frame =kcollectionFrame;

    //init UICollectionViewFlowLayout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.itemSize = CGSizeMake((frame.size.width-2.0f)/3.0f, 50);
    flowLayout.headerReferenceSize = CGSizeMake(frame.size.width, 33);
    flowLayout.footerReferenceSize = CGSizeMake(frame.size.width, 20);
    
    //init UICollectionView
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    collectionView.showsVerticalScrollIndicator = NO;
    collectionView.showsHorizontalScrollIndicator = NO;
    collectionView.backgroundColor = [UIColor whiteColor];
    
    [collectionView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellWithReuseIdentifier:@"setTimeCellId"];
    [collectionView registerNib:[UINib nibWithNibName:headerId bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];
    [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerId];
    
    
    collectionView.allowsMultipleSelection = YES;
    
   
    collectionView.contentInset = UIEdgeInsetsMake(-40, 0, 0, 0);
    _collectionView = collectionView;
    [self.view addSubview:collectionView];
    
    //提示视图
    
    UILabel *noteLabel =[[UILabel alloc] initWithFrame:CGRectMake(0, kScreenHeight -64 -29, kScreenWidth, 29)];
    noteLabel.text = @"注：已被预约的时间段无法修改";
    noteLabel.textAlignment =NSTextAlignmentCenter;
    noteLabel.textColor = [UIColor grayColor];
    noteLabel.font = [UIFont systemFontOfSize:13];
    noteLabel.backgroundColor = HexRGB_WSJ(236, 236, 236);;
    [self.view addSubview:noteLabel];
   
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
  
    return _tiemPeriodArray.count;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WCNSetTimeCCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"setTimeCellId" forIndexPath:indexPath];
    //
    WCNTimePeriodModel *model =_tiemPeriodArray[indexPath.row];
    if (model.isSelectItem) {
        [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    }else{
        [collectionView deselectItemAtIndexPath:indexPath animated:NO];
    }
    [cell configWithNewModel:model];
    return  cell;
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    WCNTimePeriodModel *model =_tiemPeriodArray[indexPath.row];
    model.timeType = _timeType;
    model.isSelectItem = YES;
    [collectionView reloadItemsAtIndexPaths:@[indexPath]];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    WCNTimePeriodModel *model =_tiemPeriodArray[indexPath.row];
    model.timeType = _timeType;
    model.isSelectItem = NO;
    [collectionView reloadItemsAtIndexPaths:@[indexPath]];

}





@end
